package com.yao.spider.yiyao;

import com.alibaba.excel.util.StringUtils;
import com.yao.spider.core.util.MyBatiesUtils;
import com.yao.spider.yiyao.bean.DongFMBean;
import com.yao.spider.yiyao.bean.YaoYuanWang;
import com.yao.spider.yiyao.dao.DongFMBeanDao;
import com.yao.spider.yiyao.dao.DongFMBeanDaoImpl;
import com.yao.spider.yiyao.dao.YaoYuanWangDao;
import com.yao.spider.yiyao.dao.YaoYuanWangDaoImpl;
import com.yao.spider.yiyao.util.ExcelUtil;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.ibatis.session.SqlSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class YaoYuanWangMain {
    public static void getExpl() {

        List<YaoYuanWang> medicineNameExcelBeans = ExcelUtil.readMedicineNameExcel("D:\\kaifa\\医保\\国产药品说明\\药瓶说明8.xlsx");
        YaoYuanWangDao fastMailDao = new YaoYuanWangDaoImpl();
        SqlSession sqlSession = MyBatiesUtils.getSqlSession();

        fastMailDao.batchInsert(medicineNameExcelBeans, sqlSession);
    }

    public static void retry() {
        SqlSession sqlSession = MyBatiesUtils.getSqlSession();
        YaoYuanWangDao fastMailDao = new YaoYuanWangDaoImpl();
        List<YaoYuanWang> yaoYuanWangs = fastMailDao.selectUrlIsNull(sqlSession);
        for (YaoYuanWang yaoYuanWang : yaoYuanWangs) {
            String shiY = smDetail(yaoYuanWang.getMedicineUrl());
            if (!StringUtils.isEmpty(shiY)) {
                fastMailDao.updateShiY(yaoYuanWang.getId(), shiY, sqlSession);
            }
        }
    }

    public static String smDetail(String urlPath) {
        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .headers(Headers.of(HttpUtil.buildYpExplanationHeaderMap()))
                .url("https://www.yaopinnet.com/" + urlPath)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
                Document parse = Jsoup.parse(response.body().string());
                Elements allSm = parse.select("li[class='smsli']");
                for (Element element : allSm) {
                    String text = element.text();
                    if (text.contains("适应症") || text.contains("功能主治")) {
                        System.out.println(text);
                        return text;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        retry();
//        getExpl();
    }
}
